<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-button type="primary" @click="addRolesClick">添加角色</el-button>
      <el-table :data="rolesList" style="width: 100%" border>
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限渲染 -->
            <el-row
              :class="['bottom-border', index === 0 ? 'top-border' : '']"
              v-for="(item, index) in scope.row.children"
              :key="index"
            >
              <el-col :span="7">
                <el-tag closable @close="removeRoles(scope.row, item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限部分 -->
              <el-col :span="17">
                <!-- 二级权限渲染 -->
                <el-row
                  :class="[index2 === 0 ? '' : 'top-border']"
                  v-for="(item2, index2) in item.children"
                  :key="index2"
                >
                  <el-col :span="9">
                    <el-tag
                      closable
                      type="success"
                      @close="removeRoles(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限渲染 -->
                  <el-col :span="15">
                    <el-tag
                      closable
                      type="warning"
                      v-for="(item3, index3) in item2.children"
                      :key="index3"
                      @close="removeRoles(scope.row, item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="80px"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoles(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoles(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="getAllRights(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色和编辑角色部分 -->
    <el-dialog
      :title="flag ? '编辑用户' : '添加用户'"
      :visible.sync="RolesdialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form ref="rolesForm" :model="RolesForm" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="RolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="RolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddRoles">取 消</el-button>
        <el-button type="primary" @click="RolesOk">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹出框 -->
    <el-dialog title="分配权限" :visible.sync="allocationRoles" width="50%" :before-close="handleClose">
      <!-- 树形控件 -->
      <el-tree
        :data="data"
        :props="defaultProps"
        @node-click="handleNodeClick"
        show-checkbox
        :default-expand-all="true"
        node-key="id"
        :default-checked-keys="threeRoles"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allocationRoles = false">取 消</el-button>
        <el-button type="primary" @click="setRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllRolesApi,
  addRolesApi,
  queryRolesApi,
  editRolesApi,
  getAllRightsApi,
  removeRolesApi,
  getAllTreeRightsApi,
  deleteRolesApi,
  setRolesApi
} from "../api/index.js";
export default {
  data: function() {
    return {
      // 判断是编辑框还是添加的框的标志符
      flag: false,
      // 所有角色列表的数据
      rolesList: [],
      // 控制添加角色和编辑角色的模态框显示与隐藏
      RolesdialogVisible: false,
      // 分配权限的模态框显示与隐藏
      allocationRoles: false,
      // 编辑表单和添加表单数据
      RolesForm: {
        id: "",
        roleName: "",
        roleDesc: ""
      },
      // 分配权限的树形数据结构
      data: [],
      // 树形结构的配置
      defaultProps: {
        children: "children",
        label: "authName"
      },
      // 默认选中的三级权限数组
      threeRoles: [],
      // 角色分配请求需要的id
      setId: ''
    };
  },
  created() {
    this.getAllRolesList();
  },
  methods: {
    // 获取所有角色列表
    async getAllRolesList() {
      const { data: res } = await getAllRolesApi();
      this.rolesList = res.data;
    },
    // 添加角色和编辑角色提交部分
    async RolesOk() {
      if (!this.flag) {
        const { data: res } = await addRolesApi(this.RolesForm);
        if (res.meta.status !== 201) return this.$message.error("创建角色失败");
        this.$message.success("创建角色成功");
      } else {
        const { data: res } = await editRolesApi(this.RolesForm);
        if (res.meta.status !== 200) return this.$message.error("编辑角色失败");
        this.$message.success("编辑角色成功");
      }
      this.cancelAddRoles();
      this.RolesdialogVisible = false;
      this.getAllRolesList();
    },
    // 切换到添加用户的弹出框
    addRolesClick() {
      this.flag = false;
      this.RolesdialogVisible = true;
    },
    // 选择取消清空输入框
    cancelAddRoles() {
      this.RolesForm.roleName = "";
      this.RolesForm.roleDesc = "";
      this.RolesdialogVisible = false;
    },
    handleClose() {
      this.cancelAddRoles();
      // 切换分配权限的显示与隐藏
      this.allocationRoles = false;
      // 监听关闭按钮，在关闭之后初始化树形结构数据
      this.threeRoles = [];
    },
    // 编辑角色部分 根据id将数据渲染到输入框内
    async editRoles(id) {
      this.flag = true;
      this.RolesdialogVisible = true;
      this.RolesForm.id = id;
      const { data: res } = await queryRolesApi(id);
      this.RolesForm.roleName = res.data.roleName;
      this.RolesForm.roleDesc = res.data.roleDesc;
    },
    // 删除角色部分
    async deleteRoles(id) {
      const delConfirm = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (!delConfirm == "confirm") return this.$message.info("取消删除");
      const { data: res } = await deleteRolesApi(id);
      if (res.meta.status !== 200) return;
      this.$message.success("删除成功");
      this.getAllRolesList();
    },
    // 移除角色权限部分
    async removeRoles(role, rightId) {
      const confirmRes = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(confirmRes);
      if (confirmRes !== "confirm") return this.$message.info("取消删除操作！");
      const { data: res } = await removeRolesApi(role, rightId);
      console.log(res); // 未写完
      if (res.meta.status !== 200) return this.$message.error("删除权限失败");
      role.children = res.data;
    },
    // 获取所有分配权限列表
    async getAllRights(row) {
      this.setId = row.id
      const { data: res } = await getAllTreeRightsApi();
      if (res.meta.status !== 200)
        return this.$message.error("获取权限列表失败");
      // console.log(res);
      this.data = res.data;
      // 调用递归函数
      this.getThreeRoles(row, this.threeRoles);
      this.allocationRoles = true;
    },
    // 通过递归获取角色所有的三级权限
    getThreeRoles(node, arr) {
      // 如果node.children 不存在 那么就代表是在第三级权限内
      if (!node.children) {
        return arr.push(node.id);
      }
      // 如果没有return 就代表不在第三级权限内 依然还有children 所以需要进行遍历循环
      node.children.forEach(value => this.getThreeRoles(value, arr));
    },
    // 树形控件组件配置
    handleNodeClick(data) {
      // console.log(data);
    },
    // 给角色分配权限的函数
    async setRoles() {
      const treeArr = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const treeStr = treeArr.join(',')
      // console.log(treeStr);
      const {data: res} = await setRolesApi(this.setId, treeStr)
      if(res.meta.status !== 200) return this.$message.error('角色授权失败')
      this.$message.success('角色授权成功')
      this.getAllRolesList();
      this.handleClose()
    }
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.top-border {
  border-top: 1px solid #eee;
}
.bottom-border {
  border-bottom: 1px solid #eee;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>
